function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); }
var _excluded = ["children", "__update__"],
  _excluded2 = ["busKey", "busFields"];
function _toConsumableArray(arr) { return _arrayWithoutHoles(arr) || _iterableToArray(arr) || _unsupportedIterableToArray(arr) || _nonIterableSpread(); }
function _nonIterableSpread() { throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); }
function _unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === "string") return _arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); }
function _iterableToArray(iter) { if (typeof Symbol !== "undefined" && iter[Symbol.iterator] != null || iter["@@iterator"] != null) return Array.from(iter); }
function _arrayWithoutHoles(arr) { if (Array.isArray(arr)) return _arrayLikeToArray(arr); }
function _arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) arr2[i] = arr[i]; return arr2; }
function ownKeys(e, r) { var t = Object.keys(e); if (Object.getOwnPropertySymbols) { var o = Object.getOwnPropertySymbols(e); r && (o = o.filter(function (r) { return Object.getOwnPropertyDescriptor(e, r).enumerable; })), t.push.apply(t, o); } return t; }
function _objectSpread(e) { for (var r = 1; r < arguments.length; r++) { var t = null != arguments[r] ? arguments[r] : {}; r % 2 ? ownKeys(Object(t), !0).forEach(function (r) { _defineProperty(e, r, t[r]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys(Object(t)).forEach(function (r) { Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r)); }); } return e; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, _toPropertyKey(descriptor.key), descriptor); } }
function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); Object.defineProperty(Constructor, "prototype", { writable: false }); return Constructor; }
function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); Object.defineProperty(subClass, "prototype", { writable: false }); if (superClass) _setPrototypeOf(subClass, superClass); }
function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }
function _createSuper(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct(); return function _createSuperInternal() { var Super = _getPrototypeOf(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn(this, result); }; }
function _possibleConstructorReturn(self, call) { if (call && (_typeof(call) === "object" || typeof call === "function")) { return call; } else if (call !== void 0) { throw new TypeError("Derived constructors may only return object or undefined"); } return _assertThisInitialized(self); }
function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; }
function _isNativeReflectConstruct() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); return true; } catch (e) { return false; } }
function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); }
function _defineProperty(obj, key, value) { key = _toPropertyKey(key); if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }
function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == _typeof(i) ? i : String(i); }
function _toPrimitive(t, r) { if ("object" != _typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != _typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); }
function _objectWithoutProperties(source, excluded) { if (source == null) return {}; var target = _objectWithoutPropertiesLoose(source, excluded); var key, i; if (Object.getOwnPropertySymbols) { var sourceSymbolKeys = Object.getOwnPropertySymbols(source); for (i = 0; i < sourceSymbolKeys.length; i++) { key = sourceSymbolKeys[i]; if (excluded.indexOf(key) >= 0) continue; if (!Object.prototype.propertyIsEnumerable.call(source, key)) continue; target[key] = source[key]; } } return target; }
function _objectWithoutPropertiesLoose(source, excluded) { if (source == null) return {}; var target = {}; var sourceKeys = Object.keys(source); var key, i; for (i = 0; i < sourceKeys.length; i++) { key = sourceKeys[i]; if (excluded.indexOf(key) >= 0) continue; target[key] = source[key]; } return target; }
import { Table } from "../../functionalComponent/table";
import { compHoc, iup, IUPComponent } from "../../util";
import { jsx as _jsx } from "react/jsx-runtime";
var defaultResponse = function defaultResponse(res) {
  if (res && res.hasOwnProperty('total')) {
    return res;
  } else if (res && res.hasOwnProperty('totalRows') && res.hasOwnProperty('Record')) {
    return {
      total: res.totalRows,
      list: res.Record
    };
  } else {
    return res || [];
  }
};

/**
 * 过滤数据行字段
 * @param row 原始数据行
 * @param busFields 业务字段
 * @param keyValues 主键值
 * @param dataIndexMap
 * @param exclude
 */
function filterRowByBusFields(row, busFields, keyValues, dataIndexMap) {
  var exclude = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : [];
  var fields = busFields || Object.keys(row);
  var newData = {};
  fields.forEach(function (c) {
    var _dataIndexMap$c;
    !exclude.includes(c) && (newData[c] = iup.convertData(row[c], dataIndexMap === null || dataIndexMap === void 0 || (_dataIndexMap$c = dataIndexMap[c]) === null || _dataIndexMap$c === void 0 ? void 0 : _dataIndexMap$c.valueType));
  });
  newData.key = keyValues;
  return newData;
}

/**
 * 展平数据行
 */
function flatRows(rows) {
  var tmpRows = [];
  rows === null || rows === void 0 || rows.forEach(function (_ref) {
    var children = _ref.children,
      __update__ = _ref.__update__,
      row = _objectWithoutProperties(_ref, _excluded);
    tmpRows.push(row);
    (children === null || children === void 0 ? void 0 : children.length) && Array.prototype.push.apply(tmpRows, flatRows(children));
  });
  return tmpRows;
}
function areEqual(oldRow, newRow, exceptFields) {
  var oldKeys = Object.keys(oldRow).filter(function (k) {
    return !exceptFields.includes(k);
  });
  var newKeys = Object.keys(newRow).filter(function (k) {
    return !exceptFields.includes(k);
  });
  if (oldKeys.length !== newKeys.length) {
    return false;
  }
  return !newKeys.some(function (p) {
    return iup.jsonString(newRow[p]) !== iup.jsonString(oldRow[p]);
  });
}

/**
 * 面向业务的Grid组件
 * @param busKey 业务主键
 * @param busFields 业务字段，用于返回数据行时字段过滤（默认返回全部字段）
 */
export var Grid = compHoc( /*#__PURE__*/function (_IUPComponent) {
  _inherits(_class2, _IUPComponent);
  var _super = _createSuper(_class2);
  function _class2(props) {
    var _this;
    _classCallCheck(this, _class2);
    _this = _super.call(this, props);
    _defineProperty(_assertThisInitialized(_this), "busKey", void 0);
    _defineProperty(_assertThisInitialized(_this), "_initRows", undefined);
    _this.busKey = props.busKey;
    return _this;
  }
  _createClass(_class2, [{
    key: "getBusKey",
    value: function getBusKey() {
      return this.busKey || this._compIns.getApi(false).getKeyField();
    }

    /**
     * 获取子表的数据源属性
     */
  }, {
    key: "_getSubTableDataKeys",
    value: function _getSubTableDataKeys(subTable) {
      return subTable ? Object.keys(subTable).map(function (id) {
        return subTable[id].dataSource[0];
      }) : [];
    }
  }, {
    key: "_getSubTableDataIndexMap",
    value: function _getSubTableDataIndexMap(id) {
      var _iup$getCmpApi;
      return ((_iup$getCmpApi = iup.getCmpApi(id)) === null || _iup$getCmpApi === void 0 ? void 0 : _iup$getCmpApi.getDataIndexMap()) || {};
    }
  }, {
    key: "_getSubKeyFields",
    value: function _getSubKeyFields(id) {
      var api = iup.getCmpApi(id);
      if (api) {
        return [api.getCheckBoxDataIndex(), api.getExpandField()];
      }
      return [];
    }
  }, {
    key: "_loopSubTableByRowState",
    value: function _loopSubTableByRowState(parent, subTable, rowState, oldParent) {
      var _this2 = this;
      if (subTable) {
        var subIds = Object.keys(subTable);
        if (subIds.length > 0) {
          var ret = {
            subTable: {}
          };
          var subTableDataKeys = this._getSubTableDataKeys(subTable);
          Object.keys(subTable).forEach(function (id) {
            var _iup$getCmpApi2, _iup$getCmpApi3;
            var rows = flatRows(parent[subTable[id].dataSource[0]]);
            var busKey = subTable[id].busKey || ((_iup$getCmpApi2 = iup.getCmpApi(id)) === null || _iup$getCmpApi2 === void 0 ? void 0 : _iup$getCmpApi2.getProps().busKey) || ((_iup$getCmpApi3 = iup.getCmpApi(id)) === null || _iup$getCmpApi3 === void 0 ? void 0 : _iup$getCmpApi3.getKeyField());
            if (rowState === 'modifiedRow') {
              var _iup$getCmpApi4;
              var oldRows = flatRows(oldParent === null || oldParent === void 0 ? void 0 : oldParent[subTable[id].dataSource[0]]);
              ret.subTable[id] = _this2._getResultTable({
                newRows: rows,
                oldRows: oldRows,
                busKey: busKey,
                exceptFields: _this2._getSubKeyFields(id),
                dataIndexMap: _this2._getSubTableDataIndexMap(id),
                subTable: (_iup$getCmpApi4 = iup.getCmpApi(id)) === null || _iup$getCmpApi4 === void 0 ? void 0 : _iup$getCmpApi4.getProps().subTable
              });
            } else {
              ret.subTable[id] = {
                isChanged: rowState !== 'unChangedRow' && rows.length > 0,
                table: _defineProperty({
                  key: busKey
                }, rowState, rows.map(function (row) {
                  var _iup$getCmpApi5, _iup$getCmpApi6;
                  return _objectSpread({
                    row: filterRowByBusFields(row, subTable[id].busFields || ((_iup$getCmpApi5 = iup.getCmpApi(id)) === null || _iup$getCmpApi5 === void 0 ? void 0 : _iup$getCmpApi5.getProps().busFields), null, _this2._getSubTableDataIndexMap(id), [_this2._getSubKeyFields(id)].concat(_toConsumableArray(subTableDataKeys)))
                  }, _this2._loopSubTableByRowState(row, (_iup$getCmpApi6 = iup.getCmpApi(id)) === null || _iup$getCmpApi6 === void 0 ? void 0 : _iup$getCmpApi6.getProps().subTable, rowState));
                }))
              };
            }
          });
          return ret;
        }
      }
      return {};
    }
  }, {
    key: "_getResultTable",
    value: function _getResultTable(_ref2) {
      var _this3 = this;
      var newRows = _ref2.newRows,
        oldRows = _ref2.oldRows,
        busKey = _ref2.busKey,
        exceptFields = _ref2.exceptFields,
        dataIndexMap = _ref2.dataIndexMap,
        subTable = _ref2.subTable,
        _ref2$ignoreUnChanged = _ref2.ignoreUnChanged,
        ignoreUnChanged = _ref2$ignoreUnChanged === void 0 ? false : _ref2$ignoreUnChanged;
      var subTableDataKeys = this._getSubTableDataKeys(subTable);
      var busKeys = iup.isSymbol(busKey) ? [busKey] : iup.split(busKey);
      var filterFields = [].concat(_toConsumableArray(exceptFields), _toConsumableArray(subTableDataKeys));
      var result = {
        isChanged: false,
        table: {
          key: busKey,
          unChangedRow: [],
          modifiedRow: [],
          newRow: [],
          deletedRow: []
        }
      };
      var oldMap = new Map();
      oldRows.forEach(function (r) {
        var values = busKeys.reduce(function (p, c) {
          if (!iup.isNullOrEmpty(r[c]) && !(r[c] + '').endsWith('_$_')) {
            p.push(r[c]); // 原始数据主键为空时为无效数据
          }
          return p;
        }, []);
        values.length === busKeys.length && oldMap.set(values.join(','), r);
      });
      newRows.forEach(function (dataRow) {
        var values = busKeys.reduce(function (p, c) {
          var _dataRow$c;
          p.push((_dataRow$c = dataRow[c]) !== null && _dataRow$c !== void 0 ? _dataRow$c : '');
          return p;
        }, []).join(',');
        if (oldMap.has(values)) {
          var oldRow = oldMap.get(values);
          if (areEqual(oldRow, dataRow, exceptFields)) {
            // 未更新的数据行
            !ignoreUnChanged && result.table.unChangedRow.push(_objectSpread({
              row: filterRowByBusFields(dataRow, _this3.props.busFields, values, dataIndexMap, filterFields)
            }, _this3._loopSubTableByRowState(dataRow, subTable, 'unChangedRow')));
          } else {
            // 更新的数据行
            result.table.modifiedRow.push(_objectSpread({
              row: filterRowByBusFields(dataRow, _this3.props.busFields, values, dataIndexMap, filterFields)
            }, _this3._loopSubTableByRowState(dataRow, subTable, 'modifiedRow', oldRow)));
          }
          // 删除已经处理的行，剩下的为删除状态
          oldMap.delete(values);
        } else {
          // 新增的数据行
          result.table.newRow.push(_objectSpread({
            row: filterRowByBusFields(dataRow, _this3.props.busFields, null, dataIndexMap, [].concat(_toConsumableArray(busKeys), _toConsumableArray(filterFields)))
          }, _this3._loopSubTableByRowState(dataRow, subTable, 'newRow')));
        }
      });
      oldMap.forEach(function (row) {
        // 删除的数据行
        result.table.deletedRow.push(_objectSpread({
          row: filterRowByBusFields(row, _this3.props.busFields, busKeys.map(function (k) {
            return row[k] || '';
          }).join(','), dataIndexMap, filterFields)
        }, _this3._loopSubTableByRowState(row, subTable, 'deletedRow')));
      });
      ['newRow', 'modifiedRow', 'deletedRow', 'unChangedRow'].forEach(function (key) {
        if (result.table[key].length === 0) {
          delete result.table[key];
        } else if (key !== 'unChangedRow') {
          result.isChanged = true;
        }
      });
      if (ignoreUnChanged) {
        delete result.table.unChangedRow;
      }
      return result;
    }

    /**
     * 返回行状态全是新增的json格式数据【返回格式同ExtUx.js的GetAllGridData方法】
     */
  }, {
    key: "getAllDataForNew",
    value: function getAllDataForNew() {
      var _this4 = this;
      var simple = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : true;
      var subTable = this.props.subTable;
      var _this$_compIns$getApi = this._compIns.getApi(false),
        getStore = _this$_compIns$getApi.getStore,
        getDataIndexMap = _this$_compIns$getApi.getDataIndexMap,
        getKeyField = _this$_compIns$getApi.getKeyField;
      var _ref3 = [getStore(), getDataIndexMap(), getKeyField(), this._getSubTableDataKeys(subTable)],
        store = _ref3[0],
        dataIndexMap = _ref3[1],
        keyField = _ref3[2],
        subTableDataKeys = _ref3[3];
      var rows = flatRows(store.data);
      return {
        isChanged: rows.length > 0,
        table: {
          key: this.getBusKey(),
          newRow: rows.map(function (row) {
            return _objectSpread({
              row: filterRowByBusFields(row, _this4.props.busFields, null, dataIndexMap, [keyField].concat(_toConsumableArray(subTableDataKeys)))
            }, _this4._loopSubTableByRowState(row, subTable, 'newRow'));
          })
        }
      };
    }

    /**
     * 返回所有数据行，包含行状态
     */
  }, {
    key: "getAllData",
    value: function getAllData() {
      var ignoreUnChanged = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : false;
      var subTable = this.props.subTable;
      var _this$_compIns$getApi2 = this._compIns.getApi(false),
        getStore = _this$_compIns$getApi2.getStore,
        getDataIndexMap = _this$_compIns$getApi2.getDataIndexMap,
        getCheckBoxDataIndex = _this$_compIns$getApi2.getCheckBoxDataIndex,
        getExpandField = _this$_compIns$getApi2.getExpandField;
      var _ref4 = [getStore(), getDataIndexMap(), getCheckBoxDataIndex(), getExpandField()],
        store = _ref4[0],
        dataIndexMap = _ref4[1],
        checkDataIndex = _ref4[2],
        expandField = _ref4[3];
      var _ref5 = [flatRows(this._initRows || store.raw), flatRows(store.data)],
        raw = _ref5[0],
        data = _ref5[1];
      return this._getResultTable({
        newRows: data,
        oldRows: raw,
        busKey: this.getBusKey(),
        exceptFields: [checkDataIndex, expandField],
        dataIndexMap: dataIndexMap,
        subTable: subTable,
        ignoreUnChanged: ignoreUnChanged
      });
    }

    /**
     * 返回更新的行
     */
  }, {
    key: "getChange",
    value: function getChange() {
      var _ref6 = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {},
        initRows = _ref6.initRows,
        _ref6$flatSubTable = _ref6.flatSubTable,
        flatSubTable = _ref6$flatSubTable === void 0 ? true : _ref6$flatSubTable,
        _ref6$ignoreUnChanged = _ref6.ignoreUnChanged,
        ignoreUnChanged = _ref6$ignoreUnChanged === void 0 ? true : _ref6$ignoreUnChanged,
        _ref6$simple = _ref6.simple,
        simple = _ref6$simple === void 0 ? true : _ref6$simple;
      var subTable = this.props.subTable;
      this._initRows = initRows;
      if (subTable && flatSubTable) {
        return this._getChangeBySubTableMerge(ignoreUnChanged);
      }
      var result = this.getAllData(ignoreUnChanged);
      if (subTable && result.isChanged && ignoreUnChanged) {
        var _result$table$modifie;
        (_result$table$modifie = result.table.modifiedRow) === null || _result$table$modifie === void 0 || _result$table$modifie.forEach(function (r) {
          if (r.subTable) {
            Object.keys(r.subTable).forEach(function (subName) {
              delete r.subTable[subName].table.unChangedRow;
            });
          }
        });
      }
      if (simple) {
        return Object.keys(result.table).reduce(function (prev, key) {
          var data = result.table[key];
          if (iup.isArray(data)) {
            prev[key] = data.map(function (_ref7) {
              var row = _ref7.row;
              return row;
            });
          }
          return prev;
        }, {});
      }
      return result;
    }

    /**
     * 返回更新的行
     */
  }, {
    key: "_getChangeBySubTableMerge",
    value: function _getChangeBySubTableMerge() {
      var ignoreUnChanged = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : true;
      var subTable = this.props.subTable;
      var result = this.getAllData(ignoreUnChanged);
      if (subTable && (result.isChanged || !ignoreUnChanged)) {
        var ret = {
          isChanged: true,
          table: {
            key: result.table.key
          },
          subTable: {}
        };
        var keys = ['newRow', 'modifiedRow', 'deletedRow'];
        !ignoreUnChanged && keys.push('unChangedRow');
        keys.forEach(function (mKey) {
          if (result.table.hasOwnProperty(mKey)) {
            ret.table[mKey] = result.table[mKey].map(function (r) {
              if (r.subTable) {
                Object.keys(r.subTable).forEach(function (subName) {
                  ret.subTable[subName] = ret.subTable[subName] || {
                    isChanged: false,
                    table: {
                      key: r.subTable[subName].table.key
                    }
                  };
                  keys.forEach(function (dKey) {
                    var subData = r.subTable[subName].table;
                    if (subData.hasOwnProperty(dKey)) {
                      var data = ret.subTable[subName].table[dKey] || [];
                      Array.prototype.push.apply(data, subData[dKey]);
                      if (data.length > 0) {
                        ret.subTable[subName].isChanged = true;
                        ret.subTable[subName].table[dKey] = data;
                      }
                    }
                  });
                });
              }
              return {
                row: r.row
              };
            });
          }
        });
        return ret;
      }
      return result;
    }

    /**
     * 数据源是否变化
     */
  }, {
    key: "isChanged",
    value: function isChanged() {
      return this.getAllData(true).isChanged;
    }
  }, {
    key: "render",
    value: function render() {
      var _this$props = this.props,
        busKey = _this$props.busKey,
        busFields = _this$props.busFields,
        props = _objectWithoutProperties(_this$props, _excluded2);
      return /*#__PURE__*/_jsx(Table, _objectSpread({
        ref: this.outRef,
        cacheRaw: true,
        response: defaultResponse
      }, props));
    }
  }]);
  return _class2;
}(IUPComponent), 'Grid');